package com.jojo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.jojo.pojo.User;
import com.jojo.utils.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@Controller
@RestController
public class UserController {
    @RequestMapping("/j1")
// @ResponseBody  //不会走视图解析器,直接返回一个字符串
    public String json1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User("张三", 3, "男");
        String str = mapper.writeValueAsString(user);

//  return user.toString();
        return str;
    }

    @RequestMapping("/j2")
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        List<User> list = new ArrayList<User>();

        User user1 = new User("张三", 3, "男");
        User user2 = new User("李四", 3, "男");
        User user3 = new User("王五", 3, "男");

        list.add(user1);
        list.add(user2);
        list.add(user3);

        String str = mapper.writeValueAsString(list);
        return str;
    }

    @RequestMapping("/j3")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        // 不使用时间戳
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        // 自定义时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(sdf);

        Date date = new Date();

        return mapper.writeValueAsString(date);
        // return mapper.writeValueAsString(sdf.format(date));
    }

    @RequestMapping("/j4")
    public String json4() throws JsonProcessingException {

        Date date = new Date();
        return JsonUtil.getJson(date,"yyyy-MM-dd HH:mm:ss");
    }

    @RequestMapping("/j5")
    public String json5() throws JsonProcessingException {

        Date date = new Date();
        return JsonUtil.getJson1(date);
    }
}
